package com.xiran.todoself.Interceptor;

import com.xiran.todoself.utils.JwtUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private JwtUtils jwtUtils;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // ✅ 关键：放行 OPTIONS 预检请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true; // 直接放行，不验证 JWT
        }

        if (!(handler instanceof HandlerMethod)) return true;

        String authHeader = request.getHeader("Authorization");
        System.out.println("Authorization Header: " + authHeader); // 🔍 打印 header

        if (authHeader == null) {
            System.out.println("Header 为空"); // ❌
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        Long userId = jwtUtils.getUserId(authHeader);
        System.out.println("解析出的 userId: " + userId); // 🔍

        if (userId == null) {
            System.out.println("Token 无效或过期"); // ❌
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        return true;
    }
}
